package com.fjph.myapplication.ui

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.view.View
import android.widget.AdapterView
import com.fjph.myapplication.R
import com.fjph.myapplication.model.StoriesBean
import com.fjph.myapplication.model.ZhihuBean
import com.fjph.myapplication.ui.activity.WebViewActivity
import com.fjph.myapplication.ui.adapter.MyAdapter
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.collections.ArrayList

class MainActivity : FragmentActivity() {

    val instance by lazy { this }

    var adapter: MyAdapter? = null;
    var list = ArrayList<StoriesBean>();

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView();
    }

    private fun initView() {
        adapter = MyAdapter(instance, R.layout.zhihu_item, list);
        listview.adapter = adapter;
        getData();

        listview.setOnItemClickListener({ adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->

                val intent2 =Intent(MainActivity@this, WebViewActivity::class.java);
                intent2.putExtra("stories", list.get(i).id);
                startActivity(intent2);
        });

    }

    private fun getData() {

        OkGo.get<String>("https://news-at.zhihu.com/api/4/news/latest").execute(object : StringCallback() {

            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                super.onStart(request)
            }

            override fun onFinish() {
                super.onFinish()
            }

            override fun onError(response: Response<String>?) {
                super.onError(response)
            }

            override fun onSuccess(response: Response<String>?) {

                val data = (response?.body() ?: "");
                val bean = Gson().fromJson(data, ZhihuBean::class.javaObjectType)
                list.clear();
                list.addAll(bean.stories!!)
                adapter!!.notifyDataSetChanged();
            }

        });
    }


}



